#!/usr/bin/env python
# -*- coding:utf-8 -*-
from django.shortcuts import render,render_to_response
from backend import config,ucloud
import pprint
# Create your views here.

def servers(request):
    server_list = get_servers()
    return render_to_response('servers.html',{'server_list':server_list})

def get_servers():
    ret = dict()
    ret['servers'] = []
    #获取所有主机信息
    for region in ['cn-north-02', 'cn-north-03']:
        params = dict()
        params['Region'] = region
        params['Action'] = 'DescribeUHostInstance'
        params['Limit'] = 100
        params['Offset'] = 0
        while True:
            response = ucloud.api_client.get('/', params)
            print response
            assert response['RetCode'] == 0
            for h in response['UHostSet']:
                server = dict()
                server['tag'] = h['Tag']
                server['name'] = h['Name']
                server['remark'] = h.get('Remark')
                for ipset in h['IPSet']:
                    if ipset['Type'] == 'Private':
                        server['ip'] = ipset['IP']
                    else:
                        server['bgp'] = ipset['IP']
                server['realtime'] = config.realtime_url_template % server['ip']
                ret['servers'].append(server)
            #如果获取到的数量 小于 每次获取的最大值，break
            if response['TotalCount'] < params['Limit']:
                break
            #如果云主机的数量大于 limit ，则需要继续提供
            params['Offset'] += params['Limit']
        #对获取到的数据进行排序
        ret['servers'].sort(key=lambda i:i['tag']+i['name'])
    return ret['servers']
    pprint.pprint(ret['servers'])
if __name__ == '__main__':
      get_servers()